<template>
  <div id="s">
    <!--  基本信息-->
    <el-form :model="dispatchForm" style="text-align: left" label-width="120px">

      <div>
        <div  class="myBorder ">

          <el-row style="margin-bottom: 20px">
            <el-col :span="24"><div class="grid-content bg-purple-light">
              <div class="separate" >&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-tickets"></i>&nbsp;&nbsp;基本信息</div>
            </div></el-col>
          </el-row>
          <div style="text-align: right">

            <el-form-item>
              <el-button type="info" @click="save('待领取')" plain>提交</el-button>
              <el-button type="info" @click="save('制单')" plain>保存</el-button>
              <el-button type="info" @click="cancel" plain>取消</el-button>&nbsp;&nbsp;
            </el-form-item>
          </div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="调度单号">
                <el-input v-model="dispatchForm.ticketId" readonly style="width: 300px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人员">
                <el-input v-model="dispatchForm.createId" readonly style="width: 300px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间">
                <el-input v-model="dispatchForm.createTime" readonly style="width: 300px;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="运输类型">
                <el-select v-model="dispatchForm.type" placeholder="请选择" style="width: 300px;">
                  <el-option
                    v-for="item in typeList"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="车牌号">
                <el-select v-model="dispatchForm.carInfo" placeholder="请选择" @change="getDriverAndCar($event)"
                           value-key="id" filterable style="width: 300px;">
                  <el-option
                    v-for="item in carList"
                    :key="item.id"
                    :label="item.number"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发货时间">
                <el-date-picker style="width: 300px;"
                                v-model="dispatchForm.startTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择日期"
                                :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="预计到达时间">
                <el-date-picker style="width: 300px;"
                                v-model="dispatchForm.endTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择日期"
                                :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="起点" prop="consignorAddress">
                <el-cascader
                  v-model="dispatchForm.startAreaId"
                  :options="baseCityList"
                  :props="props"
                  filterable
                  style="width: 300px;"></el-cascader>
              </el-form-item>
              <el-form-item label="终点" prop="consigneeAddress">
                <el-cascader
                  v-model="dispatchForm.endAreaId"
                  :options="baseCityList"
                  :props="props"
                  filterable
                  style="width: 300px;">
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="myBorder ">
        <el-row style="margin-bottom: 20px">
          <el-col :span="24"><div class="grid-content bg-purple-light">
            <div class="separate" >&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-tickets"></i>&nbsp;&nbsp;车辆信息</div>
          </div></el-col>
        </el-row>
        <el-descriptions class="margin-top" :column="3" border>
          <el-descriptions-item>
            <template slot="label">
              车辆长度(m)
            </template>
            {{ this.car.length }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车辆宽度(m)
            </template>
            {{ this.car.width }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车辆高度(m)
            </template>
            {{ this.car.height }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车辆类型
            </template>
            {{ this.car.type }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              载重量(吨)
            </template>
            {{ this.car.carLoad }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车辆容积(m³)
            </template>
            {{ this.car.volume }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车辆当前位置
            </template>
            {{ this.car.location }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              车牌号
            </template>
            {{ this.car.number }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              司机姓名
            </template>
            {{ this.driver.driverName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              司机性别
            </template>
            {{ this.driver.sex }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              联系方式
            </template>
            {{ this.driver.driverTel }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              身份证号
            </template>
            {{ this.driver.driverId }}
          </el-descriptions-item>
        </el-descriptions>

      </div>
      <div class="myBorder ">
        <el-row style="margin-bottom: 20px">
          <el-col :span="24"><div class="grid-content bg-purple-light">
            <div class="separate" >&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-tickets"></i>&nbsp;&nbsp;订单信息</div>
          </div></el-col>
        </el-row>

        <div>
          <el-form :inline="true" style="text-align: right">
            <el-form-item>
              <el-form-item label="总重量(kg)" prop="weight">
                <el-input readonly v-model="weight"></el-input>
              </el-form-item>
              <el-form-item label="总体积(m³)" prop="weight">
                <el-input readonly v-model="volume"></el-input>
              </el-form-item>
              <el-button type="info" @click="addOrder" plain>新增</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <!--          订单数据表格-->
          <el-table :data="dispatchForm.orderFormList" stripe style="width: 100%"
                    :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
            <el-table-column
              label="序号"
              width="80"
              type="index"
              fixed>
            </el-table-column>
            <el-table-column
              prop="orderId"
              label="委托单编号"
              sortable
              width="180">
            </el-table-column>
            <el-table-column
              prop="customer.customerNameShort"
              label="委托客户"
              width="180">
            </el-table-column>
            <el-table-column
              prop="transportType"
              label="订单类型"
              width="100">
            </el-table-column>
            <el-table-column
              prop="weight"
              label="重量(kg)"
              width="100">
            </el-table-column>
            <el-table-column
              prop="volume"
              label="体积(m³)"
              width="100">
            </el-table-column>
            <el-table-column
              prop="consignorName"
              label="发货人"
              width="100">
            </el-table-column>
            <el-table-column
              prop="consignorCity.mergerName"
              label="发货地址"
              width="180">
            </el-table-column>
            <el-table-column
              prop="consigneeName"
              label="收货人"
              width="100">
            </el-table-column>
            <el-table-column
              prop="consigneeCity.mergerName"
              label="收货地址"
              width="180">
            </el-table-column>
            <el-table-column
              prop="pickupDate"
              label="取货日期"
              sortable
              width="180">
            </el-table-column>
            <el-table-column
              prop="currentStatus"
              label="当前状态"
              width="100">
            </el-table-column>
            <el-table-column
              label="操作"
              width="180">
              <template v-slot="scope">
                <el-popconfirm title="确定删除吗？" @confirm="remove(scope.row)">
                  <el-button slot="reference" type="text" size="small">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="myBorder ">
        <el-row style="margin-bottom: 20px">
          <el-col :span="24"><div class="grid-content bg-purple-light">
            <div class="separate" >&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-tickets"></i>&nbsp;&nbsp;路线信息</div>
          </div></el-col>
        </el-row>
        <div style="text-align: right">

          <el-button type="info" @click="showRoute=true" plain>新增</el-button>&nbsp;&nbsp;

        </div>
        <br/>
        <div>
          <el-table :data="dispatchForm.dispatchRouteList" stripe style="width: 100%"
                    :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
            <el-table-column
              label="序号"
              width="80"
              type="index"
              fixed>
            </el-table-column>
            <el-table-column
              label="起点"
              prop="lastId"
              :formatter="getCityName"
            >
            </el-table-column>
            <el-table-column
              label="终点"
              prop="areaId"
              :formatter="getCityName"
            >
            </el-table-column>
            <el-table-column
              label="到达时间"
              prop="ariveTime"
            >
            </el-table-column>
            <el-table-column
              label="操作"
              width="180">
              <template v-slot="scope">
                <el-popconfirm title="确定删除吗？" @confirm="removeRoute(scope.row)">
                  <el-button slot="reference" type="text" size="small">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form>
    <el-dialog
      title="订单"
      :visible.sync="showOrder"
      width="70%">
      <div slot="footer" class="dialog-footer">
        <!--  查询条件-->
        <el-form :inline="true" :model="queryForm" style="text-align: left">
          <el-form-item label="委托单号">
            <el-input v-model="queryForm.orderId" placeholder="委托单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="发货人">
            <el-input v-model="queryForm.consignorName" placeholder="发货人" clearable></el-input>
          </el-form-item>
          <el-form-item label="收货人">
            <el-input v-model="queryForm.consigneeName" placeholder="收货人" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="getOrderList" plain>查询</el-button>
          </el-form-item>
        </el-form>
        <!--  表格-->
        <el-table :data="tableData" stripe style="width: 100%"
                  :header-cell-style="{background:'#f7f7f7', color:'#666666'}" @selection-change="handleSelectionChange"
                  ref="multipleTable">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="序号"
            width="80"
            type="index"
            :index="No"
            fixed>
          </el-table-column>
          <el-table-column
            prop="orderId"
            label="委托单编号"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="customer.customerNameShort"
            label="委托客户"
            width="180">
          </el-table-column>
          <el-table-column
            prop="transportType"
            label="订单类型"
            width="100">
          </el-table-column>
          <el-table-column
            prop="weight"
            label="重量(kg)"
            width="100">
          </el-table-column>
          <el-table-column
            prop="volume"
            label="体积(m³)"
            width="100">
          </el-table-column>
          <el-table-column
            prop="consignorName"
            label="发货人"
            width="100">
          </el-table-column>
          <el-table-column
            prop="consignorCity.mergerName"
            label="发货地址"
            width="180">
          </el-table-column>
          <el-table-column
            prop="consigneeName"
            label="收货人"
            width="100">
          </el-table-column>
          <el-table-column
            prop="consigneeCity.mergerName"
            label="收货地址"
            width="180">
          </el-table-column>
          <el-table-column
            prop="pickupDate"
            label="取货日期"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="currentStatus"
            label="当前状态"
            width="100">
          </el-table-column>
        </el-table>
        <!--  分页-->
        <div style="width: 65%;">
          <el-pagination
            @size-change="getOrderList"
            @current-change="getOrderList"
            :current-page.sync="queryForm.pageNum"
            :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
            :page-size.sync="queryForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
        <el-button @click="cancleOrder"  type="info" plain>取 消</el-button>
        <el-button type="info" @click="confirmOrder" plain>确 定</el-button>
      </div>
    </el-dialog>
    <!--    编辑路线-->
    <el-dialog
      title="路线"
      :visible.sync="showRoute"
      width="30%">
      <span>
        <el-form :model="routeForm" label-width="120px">

          <el-form-item label="起点" prop="consignorAddress">
            <el-cascader
              v-model="routeForm.lastId"
              :options="baseCityList"
              :props="props"
              filterable
              style="width: 300px;"></el-cascader>
          </el-form-item>
          <el-form-item label="终点" prop="consignorAddress">
            <el-cascader
              v-model="routeForm.areaId"
              :options="baseCityList"
              :props="props"
              filterable
              style="width: 300px;"></el-cascader>
          </el-form-item>
          <el-form-item label="预计到达时间">
            <el-date-picker style="width: 300px;"
                            v-model="routeForm.ariveTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期"
                            :picker-options="pickerOptions">
            </el-date-picker
            >
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRoute = false" type="info" plain>取 消</el-button>
        <el-button type="info" @click="routeSubmit()" plain>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "DispatchEdit",
  data() {
    return {
      //格式化级联选择器属性
      props: {
        value: 'id',
        label: 'cityName',
        children: 'cityChildrenList',
        checkStrictly: true,   //若为false则必须为顺序选择才能显示
        emitPath: false     // false只获得最近一层父级， ture 获得所有父级
      },
      //车辆列表
      carList: [],
      //调度单查询条件
      dispatchForm: {
        type: '整车',
        orderFormList: [],
        dispatchRouteList: [],
        carInfo: {}
      },
      //订单查询条件
      queryForm: {
        orderId: '',
        consignorName: '',
        consigneeName: '',
        pageNum: 1,
        pageSize: 10,
        currentStatus: '待调度'
      },
      //表格数组
      tableData: [],
      //共多少条
      total: 0,
      //显示修改删除按钮
      show: false,
      //运输类型
      typeList: ['整车', '散货'],
      //城市列表
      baseCityList: [],
      //选中车牌号车辆信息
      car: {},
      //选中车牌号司机信息
      driver: {},
      //订单弹窗控制
      showOrder: false,
      //调度单总重量
      weight: 0,
      //调度单总体积
      volume: 0,
      //选中订单组
      selectRows: [],
      //路线弹窗控制
      showRoute: false,
      //路线表单
      routeForm: {},
      //日期快捷选项
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
    }
  },
  methods: {
    //不丢失精度加法
    accAdd(arg1, arg2) {
      let r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split('.')[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      n = r1 >= r2 ? r1 : r2
      return +((arg1 * m + arg2 * m) / m).toFixed(n)
    },
    //不丢失精度减法
    accSub(arg1, arg2) {
      let r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split('.')[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      n = r1 >= r2 ? r1 : r2
      return +((arg1 * m - arg2 * m) / m).toFixed(n)
    },
    //添加订单
    addOrder() {
      this.showOrder = true;
      this.getOrderList();
    },
    //勾选订单对象变化时出发
    handleSelectionChange(val) {
      this.selectRows = val;
    },
    //取消添加订单
    cancleOrder() {
      this.selectRows = [];
      this.showOrder = false;
    },
    //确认添加订单
    confirmOrder() {
      for (let order of this.selectRows) {
        if (this.dispatchForm.orderFormList.indexOf(order) == -1) {
          this.dispatchForm.orderFormList.push(order);
          this.weight = this.accAdd(this.weight, order.weight);
          this.volume = this.accAdd(this.volume, order.volume);
        } else {
          this.$message.info("不能重复添加")
        }
      }
      this.showOrder = false;
    },
    //删除订单
    remove(row) {
      this.dispatchForm.orderFormList.splice(this.dispatchForm.orderFormList.indexOf(row), 1)
      this.weight = this.accSub(this.weight, row.weight);
      this.volume = this.accSub(this.volume, row.volume);
    },
    //分页表格递增排序
    No(index) {
      // 当前页数 - 1 * 每页数据条数 + 1
      const page = this.queryForm.pageNum // 当前页码
      const pageSize = this.queryForm.pageSize // 每页条数
      return (page - 1) * pageSize + index + 1
    },
    //根据id获取车辆信息和司机信息
    getDriverAndCar(val) {
      let carId = val.id
      this.$axios({
        url: 'car/getDriverAndCar/' + carId,
        method: 'post',
      }).then(res => {
        if (res.data.success) {
          if (res.data.object.car.carStatus == '空闲') {
            this.car = res.data.object.car;
            this.driver = res.data.object.driver;
          }
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //获取所有城市
    getCityList() {
      this.$axios({
        url: 'base/city/listAll',
        method: 'post'
      }).then(res => {
        this.baseCityList = res.data.object;
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    // 获取所有空闲车辆
    getCarList() {
      this.$axios({
        url: 'car/list',
        method: 'post',
        //查询所有状态为空闲的车辆
        data: {carStatus: '空闲', driverId: 200}
      }).then(res => {
        if (res.data.success) {
          this.carList = res.data.object.list;

        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //获取所有待调度订单
    getOrderList() {
      this.$axios({
        url: 'order/form/list',
        method: 'post',
        data: this.queryForm
      }).then(res => {
        if (res.data.success) {
          this.tableData = res.data.object.list;
          this.total = res.data.object.total;
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //根据城市Id获取城市名格式化列
    getCityName(row, column, cellValue, index) {
      for (let area of this.baseCityList) {
        for (let city of area.cityChildrenList) {
          if (city.id == cellValue) {
            return city.mergerName;
          }
        }
      }
    },
    //暂存或提交调度单
    save(val) {
      this.dispatchForm.status = val;
      this.$axios({
        url: 'dispatch/ticket/update',
        method: 'post',
        data: this.dispatchForm
      }).then(res => {
        if (res.data.success) {
          this.$router.back()
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //取消修改调度单
    cancel() {
      this.$router.back();
    },
    //保存路线
    routeSubmit() {
      this.routeForm.index = this.dispatchForm.dispatchRouteList.length + 1
      this.dispatchForm.dispatchRouteList.push(this.routeForm)
      this.routeForm = {}
      this.showRoute = false
    },
    //删除路线
    removeRoute(row) {
      this.dispatchForm.dispatchRouteList.splice(this.dispatchForm.dispatchRouteList.indexOf(row), 1)
    },
    // 初始化调度单对象
    iniDispatchForm() {
      this.dispatchForm = this.$store.state.currentDispatchTicket;
    },
    // 初始化订单列表
    initOrderFormList() {
      if (this.$store.state.currentDispatchTicket.orderFormList !== undefined) {
        for (let form of this.$store.state.currentDispatchTicket.orderFormList) {
          this.weight = this.accAdd(this.weight, form.weight)
          this.volume = this.accAdd(this.volume, form.volume)
        }
      }
    },
  },
  created() {
    this.iniDispatchForm();
    this.initOrderFormList();
    this.getCarList();
    this.getCityList();
    let car = this.$store.state.currentDispatchTicket.carInfo;
    if (car !== undefined && car != null) {
      if (car.carStatus != '空闲') {
        this.$message("原车辆已被派发任务")
      }
      this.getDriverAndCar(car)
    }

  },
  mounted() {
    if (this.$store.state.carInfoToDispatchEdit != '') {
      this.dispatchForm.carInfo = this.$store.state.carInfoToDispatchEdit
    }

    let temp = this.dispatchForm.carInfo;
    if (temp !== undefined && temp != null) {
      this.car = temp
    }

  },
  destroyed() {
    this.$store.commit('carInfoToDispatchEdit', '');
  }

}
</script>
<style scoped>
#s{
  width:90%;
  margin:10px auto;
  background-color: #ffffff;
  box-shadow: 10px 10px 5px #c4c6c7;
  border-radius: 5px
}
.el-button--info:hover {
  background: #209e91;
  border-color: #209e91;
  color: #FFF;
}
.myBorder {
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  margin: 20px 0px;
}
.separate {
  width: 100%;height: 50px;background: #339999;border-color: #339999;text-align: left;line-height:50px;color: #FFFFFF;
}
</style>
